//
//  QLKDataBaseManager.m
//  CloudsOutpatient
//
//  Created by zzs on 15/6/17.
//  Copyright (c) 2015年 HC. All rights reserved.
//

#import "QLKDataBaseManager.h"

 
#define pageNum  10

//测试包IM数据日子
#define IM_LOG_TABLE             @"IM_LOG_TABLE"
//数据库名
#define DB_FILE_NAME             @"QLKIOSTEAMS.sqlite"

//搜索药品历史记录
#define TABLE_searchDrugHistory           @"searchDrugHistory"

#define SQL_CREATE_searchDrugHistory  [NSString stringWithFormat : @"CREATE TABLE IF NOT EXISTS %@ (searchDrugHistory_id INTEGER PRIMARY KEY AUTOINCREMENT,content text,currTime text)" , TABLE_searchDrugHistory ]

static QLKDataBaseManager *shareDataBaseManager=nil;

@interface QLKDataBaseManager (){
  
}
//创建本地数据库
+ (NSString *) dbFilePath;
//建表方法
-  (BOOL)createTableForSql : (NSString *) tableSql;

@end

@implementation QLKDataBaseManager
+(QLKDataBaseManager*)shareDataBaseManager{
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        shareDataBaseManager = [[self alloc] init];
    });
    return shareDataBaseManager;
}

- (id) init
{
    self = [super init];
    if (self)
    {   //初始化数据库
        [self openCurrentDB];
    }
    return self;
}
#pragma mark 打开并创建表
- (void) openCurrentDB
{
    if(_database)
    {
        [_database close];
        _database = nil;
    }
    _database = [FMDatabase databaseWithPath:[QLKDataBaseManager dbFilePath]];
    if (![_database open])
    {
        QLKDLog(@"DataBaseUtil --  openCurrentDB --> 打开数据库失败");

    }
    else
    {
        _databaseQueue = dispatch_queue_create("com.qlk.dabai", NULL);
        //创建用户表
        if (![_database tableExists:TABLE_searchDrugHistory])
        {
            [self createTableForSql:SQL_CREATE_searchDrugHistory];
        }
        }
}

- (FMDatabase *)dataBase
{
    return _database;
}

#pragma mark
#pragma mark 私有方法
#pragma mark --创建于本地沙盒中数据库（私有方法）
+ (NSString *) dbFilePath
{
    NSString * directorPath = [NSString userIdExclusiveDirectionWithUserId];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL isDirector = NO;
    BOOL isExiting = [fileManager fileExistsAtPath:directorPath isDirectory:&isDirector];
    if (!(isExiting && isDirector))
    {
        BOOL creatDirection = [fileManager createDirectoryAtPath:directorPath
                                     withIntermediateDirectories:YES
                                                      attributes:nil
                                                           error:nil];
        if (!creatDirection)
        {
            QLKDLog(@"dbFilePath --> DataBaseUtil 创建数据库存储文件失败");
        }
    }
    NSString * dbPath = [directorPath stringByAppendingString:DB_FILE_NAME];
    NSLog(@"dbPath:%@",dbPath);
    return dbPath;
}

#pragma mark -- 创建表方法(私有方法)
-  (BOOL) createTableForSql : (NSString *) tableSql
{
    BOOL result = NO;
    [_database setShouldCacheStatements:YES];
    NSString * temSql = [NSString stringWithFormat:@"%@" , tableSql];
    result = [_database executeUpdate: temSql];
    if (result)
    {
        QLKDLog(@"createTableForSql 创建数据库是：%@" , temSql);
        
    }
    return result;
}

#pragma mark-搜索药品记录
-(BOOL)insertHistoryContentToDB:(NSString*)content{
    NSString *currTime = [[NSDate date] getTimestamp];
    
    FMResultSet *rs = [_database executeQuery:[NSString stringWithFormat:@"SELECT * FROM searchDrugHistory WHERE content = '%@'",content]];
    NSInteger count = 0;
    while ([rs next]) {
        count ++;
    }
    if(count == 0){
        NSString * inserUserSql = @"INSERT INTO searchDrugHistory (content,currTime) VALUES (?,?)";
        BOOL result = [_database executeUpdate:inserUserSql ,content,currTime
                       ];
        return result;
    }else{
        NSString * update = @"UPDATE searchDrugHistory SET currTime=? where content=?";
        [_database executeUpdate:update ,currTime,content];
    }
    return NO;
}
-(BOOL)deleteAllHistoryData{
    NSString * inserUserSql = @"DELETE FROM searchDrugHistory";
    BOOL result = [_database executeUpdate:inserUserSql];
    return result;

}

-(NSArray*)queyAllDrugHistoryContents{
    //定义一个可变数组，用来存放查询的结果，返回给调用者
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    //定义一个结果集，存放查询的数据
    FMResultSet *rs = [_database executeQuery:@"select * from searchDrugHistory order by currTime asc"];
    //判断结果集中是否有数据，如果有则取出数据
    while ([rs next]) {
        SearchHistoryModel *model=[[SearchHistoryModel alloc] init];
        model.historyID=[rs intForColumn:@"searchDrugHistory_id"];
        model.content=[rs stringForColumn:@"content"];
        //将查询到的数据放入数组中。
        [tempArray addObject:model];
    }
    return  tempArray;

}

@end

